package jalus.service;

import jalus.dao.TagDAO;
import jalus.model.Tag;
import jalus.pojo.Post;
import jalus.utils.MyUtils;
import jalus.utils.PojoHandler;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

/**
 * 归档服务
 * 
 *
 */
public class ArchiveService {
	private TagDAO tagDAO;
	private Cache cache;
	private static ArchiveService instance = new ArchiveService();
	private ArchiveService(){
		tagDAO = new TagDAO();
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(Collections.emptyMap());
		} catch (CacheException e) {
		}
	}
	public static ArchiveService getInstance(){
		return instance;
	}
	
	private static final String ARCHIVE = "archive";
	public static final String dateFormat = "yyyy-MM";
	
	/**
	 * 获得所有的archive列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<jalus.pojo.Tag> getAllArchiveList(){
		String key= "getAllArchiveList";
		if(!cache.containsKey(key)){
			List<jalus.pojo.Tag> tagList = PojoHandler.copyMToPList(
					this.tagDAO.getListByCidOrderByName(ARCHIVE));
			cache.put(key, tagList);
		}
		return (List<jalus.pojo.Tag>) cache.get(key);
	}

	
	/**
	 * archive计数增1
	 * @param tagName
	 */
	public void increaseCount(Date date){
		String archive = MyUtils.formatDateCCT(date, dateFormat);
		tagDAO.updateCountByName(ARCHIVE, archive, 1);
		cache.clear();
	}
	
	/**
	 * archive计数减1
	 * @param tagName
	 */
	public void decreaseCount(Date date){
		String archive = MyUtils.formatDateCCT(date, dateFormat);
		tagDAO.updateCountByName(ARCHIVE, archive, -1);
		cache.clear();
	}
	
	
	public void clearCache(){
		cache.clear();
	}
	public void reCount() {
		// TODO: 删除所有的archive
		PostService postService = PostService.getInstance();
		List<Post> postList = postService.getAllPostList();
		Map<String, Integer> map = new HashMap<String, Integer>();
		for(Post post : postList){
			String archive = MyUtils.formatDateCCT(post.getDate(), dateFormat);
			if(map.containsKey(archive)){
				map.put(archive, map.get(archive)+1);
			}else{
				map.put(archive, 1);
			}
		}
		for(String archive : map.keySet()){
			Tag tag = new Tag(ARCHIVE, archive, map.get(archive));
			this.tagDAO.addTag(tag);
		}
	}
}
